package org.finesys.common.core.util;

import lombok.experimental.UtilityClass;
import org.finesys.commom.jackson.util.JacksonUtil;
import org.finesys.common.core.module.R;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

@UtilityClass
public class WebUtil {

    /**
     * 获取 HttpServletRequest
     *
     * @return {HttpServletRequest}
     */
    public Optional<HttpServletRequest> getRequest() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        if (servletRequestAttributes == null) {
            return Optional.empty();
        }
        return Optional.of(servletRequestAttributes.getRequest());
    }

    public ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }


    /**
     * 获取RequestAttributes
     */
    private static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取响应
     *
     * @return {HttpServletResponse}
     */
    public HttpServletResponse getResponse() {
        return Objects.requireNonNull(getRequestAttributes()).getResponse();
    }

    /**
     * 设置响应
     *
     * @param response    HttpServletResponse
     * @param contentType content-type
     * @param status      http状态码
     * @param value       响应内容
     * @throws IOException IOException
     */
    public static void makeResponse(HttpServletResponse response, String contentType, int status, Object value)
            throws IOException {
        response.setContentType(contentType);
        response.setStatus(status);
        response.getOutputStream().write(JacksonUtil.toJsonString(value).getBytes());
    }

    /**
     * 设置失败响应
     *
     * @param response HttpServletResponse
     * @param result   响应内容
     * @throws IOException IOException
     */
    public static void makeFailureResponse(HttpServletResponse response, R<Void> result) throws IOException {
        makeResponse(response, MediaType.APPLICATION_JSON_VALUE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, result);
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }

}
